﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Diagnostics;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.System.UserProfile;
using System.Globalization;
using Windows.ApplicationModel.Background;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Battery_Life
{


    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        string CurrentStatus;
        int testcnt = 0;
        bool isTaskRegistered = false;
        private void CheckTaskRegistration()
        {
            var taskName = "BatteryUpdateBackgroundTask";

            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == taskName)
                {
                    isTaskRegistered = true;
                    break;
                }
            }
            if (!isTaskRegistered)
            {
                RegisterBackgroundTask(taskName, "Task.BatteryUpdateBackgroundTask");
            }
        }
        private void RegisterBackgroundTask(string name, string entrypoint)
        {
            BackgroundTaskBuilder btb = new BackgroundTaskBuilder();
            btb.Name = name;
            btb.TaskEntryPoint = entrypoint;
            //run every minute
            btb.SetTrigger(new TimeTrigger(1, false));
            btb.AddCondition(new SystemCondition(SystemConditionType.UserPresent));
            BackgroundTaskRegistration task = btb.Register();
            Debug.WriteLine("--task registered--");

        }
        
        public static class FileAsync
        {
            public static async void Read(string folderPath, string fileName,
                Action<uint, DataReader> reader)
            {
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(folderPath);

                Read(folder, fileName, reader);
            }

            public static async void Read(StorageFolder folder, string fileName,
                Action<uint, DataReader> reader)
            {
                StorageFile file;
                IRandomAccessStream stream;
                IInputStream inputStream;
                DataReader rdr;

                file = await folder.GetFileAsync(fileName);

                stream = await file.OpenAsync(FileAccessMode.Read);
                inputStream = stream.GetInputStreamAt(0);

                uint fileSize = (uint)stream.Size;

                rdr = new DataReader(inputStream);
                await rdr.LoadAsync(fileSize);

                reader(fileSize, rdr);
            }
        }

        public void CreateSchedule()
        {
            Debug.WriteLine("--createsched called--");

            DateTime now = DateTime.Now;

            var tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();

            const string xml = @"<tile><visual> 
                                        <binding template=""TileSquareText03""><text id=""1"">{0}</text></binding>
                                        <binding template=""TileWideText01""><text id=""1"">{0}</text></binding> 
                                   </visual></tile>";
                                        
            
            CurrentStatus = GetStatus();
            var tileXmlNow = string.Format(xml, CurrentStatus);
            XmlDocument documentNow = new XmlDocument();
            documentNow.LoadXml(tileXmlNow);
            Debug.WriteLine("run# " + testcnt++);

            tileUpdater.Update(new TileNotification(documentNow) { ExpirationTime = now.AddMinutes(1) });

        }

        private string GetStatus()
        {
            Debug.WriteLine("--getstatus called--");

            try
            {
                string readData = "";
                string file = @"BatteryStatus\BatteryStatus.txt";
                Debug.WriteLine("path: " + file);

                FileAsync.Read(KnownFolders.DocumentsLibrary, file, (fileSize, reader) =>
                {
                    readData = reader.ReadString(fileSize);
                    char[] delimiterChars = {' '};

                    string[] data = readData.Split(delimiterChars);
                    foreach (string i in data)
                    {
                        Debug.WriteLine("data: " + i);
                    }
                    this.percentage.Text = readData.ToString();

                    if (data.Length > 0)
                    {
                        Debug.WriteLine(data[5]);
                        CurrentStatus = data[5];
                    }
                    reader.Dispose();
                });

                Debug.WriteLine("return: " + CurrentStatus);
                return CurrentStatus.ToString();

            }
            catch (Exception e)
            {

                Debug.WriteLine("return: " + e.Message);
                return e.Message.ToString();

            }
        }

        public MainPage()
        {
            this.InitializeComponent();
            testcnt = 0;
            CurrentStatus = "Getting Info";
            //GetStatus();
            //CreateSchedule();


            
        }

        

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            CheckTaskRegistration();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CreateSchedule();
        }
    }
}
